<?php
namespace app\admin\controller;
use think\Db;
use clt\Leftnav;
use app\admin\model\Users;
use app\admin\model\AuthGroup;
use app\admin\model\authRule;
use think\Validate;
class Auth extends Common
{
    public function _initialize()
    {

        parent::_initialize();
        $this->title = lang('User List');
        $this->group_id = 1;
        $this->requestUrl = U('adminlist');
        $this->addUrl = U('adminadd');
        $this->editUrl =  U('adminEdit');
        $this->backUrl = U('adminlist');
    }
    //管理员列表
    public function adminList($sup_id=null,$isReport=null,$page=null){
        $params = $this->request->post();
        $params['isReport'] = 1;
        $page = (int)$page > 0 ? $page : 1;
        if(request()->isPost() || $isReport==1){
            $val=input('key');
            $map='';
            if($val){
                $map['a.email|a.mobile']= array('like',"%".$val."%");
            }
            if (!Users::isAdmin($this->User_id)){  //不是管理员账号
                $sup_ids = Users::getCustomerList($this->User_id);
                array_push($sup_ids, $this->User_id);
                $map['a.sup_id']=array('in',$sup_ids);
            }
            // if($this->group_id > 0){
            //     $map['a.group_id']=$this->group_id;
            // }
            $model=db('users')->alias('a')
                ->join('auth_group ag','a.group_id = ag.group_id','left')
                ->order('is_sys desc,a.email asc')
                ->field('a.*,ag.title')
                ->where($map);
             $data = [];   
            if($isReport==1){
                $data = $model->select();
                $this->exports($data); exit;
            }else{
                $lists = $model->paginate(array('list_rows'=>$this->pageSize,'page'=>$page))->toArray();
                foreach($lists['data'] as $list){
                    $list['guishu'] = getSupNameGroup($list['sup_id']);
                    $data[] =$list;
                }
            }
            return $result = ['code'=>0,'msg'=>lang('Request success.'),'data'=>$data, 'count'=> $lists['total'],'rel'=>1,'repotUrl'=>U('',$params)];
        }
        $this->assign('requestUrl',$this->requestUrl);
        $this->assign('title',$this->title);
        $this->assign('addUrl',$this->addUrl);
        $this->assign('editUrl',$this->editUrl);
        $this->assign('repotUrl',U('',$params));
        return view('adminlist');
    }
    
    /*添加管理员*/
    public function adminAdd($group_id=null){
        if(request()->isPost()){
            $data = input('post.');
            // $check_user = Users::get(['username'=>$data['username']]);
            // if ($check_user) {
            //     return $result = ['code'=>0,'msg'=>lang('The username has already existed!')];
            // }
            if(empty($data['email']) || !is_email($data['email'])){
                return array('code'=>0,'msg'=>lang('Please enter the correct mailbox address.'));
            }
            /*验证邮箱是否唯一*/
            if(Users::validEmail($data['email'])){
                return array('code'=>0,'msg'=>lang('this email has been used'));
            }
            $data['pwd'] = input('post.pwd', '', 'md5');
            $data['add_time'] = time();
            //验证
            $msg = $this->validate($data,'Users');
            
            if($msg!='true'){
                return $result = ['code'=>0,'msg'=>$msg];
            }
            $data['group_id'] = $group_id;
            //单独验证密码
            $checkPwd = Validate::is(input('post.pwd'),'require');
            if (false === $checkPwd) {
                return $result = ['code'=>0,'msg'=>lang('The password cannot be empty!')];
            }
            $data['lang'] = $this->lang;
            $data['source'] = 'CF';
            //添加
            if (Users::create($data)) {
                $data['password'] = md5($data['pwd']);
                /*同步到ucenter*/
                $ucenter = new \clt\Ucenter(); 
                $uid = $ucenter->register($data);
                return ['code'=>1,'msg'=>lang('The data is saved successfully!'),'url'=>$this->backUrl];
            } else {
                return ['code'=>0,'msg'=>lang('Data save failed!')];
            }
        }else{
            $auth_group = AuthGroup::group($this->user['group_id']);
            $this->assign('authGroup',$auth_group);
            $this->assign('title',lang('New User'));
            $this->assign('info','null');
            $this->assign('group_id',$group_id);            
            $this->assign('selected', 'null');
            $this->assign('users',Users::isAdmin($this->User_id) ? Users::getUserLists() : $this->User_id );
            return view('adminform');
        }
    }
   
    //删除管理员
    public function adminDel(){
        $admin_id=input('post.admin_id');
        $email = Users::getEmail($admin_id); 
        if (!empty($email)){
            $result = Users::destroy(['admin_id'=>$admin_id]);
            if($result){
                $ucenter = new \clt\Ucenter(); 
                $ucenter->delete($email);
            }
            return $result = ['code'=>1,'msg'=>lang('Delete success!')];
        }else{
            return $result = ['code'=>0,'msg'=>lang("sorry, you don't have permission!")];
        }
    }
    //修改管理员状态
    public function adminState(){
        $id=input('post.id');
        $is_open=input('post.is_open');
        if (empty($id)){
            $result['status'] = 0;
            $result['info'] = lang("User ID does not exist");
            $result['url'] = url('adminlist');
            return $result;
        }
        db('Users')->where('admin_id='.$id)->update(['is_open'=>$is_open]);
        $result['status'] = 1;
        $result['info'] = lang("User status modification is successful!");
        $result['url'] = url('adminlist');
        return $result;
    }
    //更新管理员信息
    public function adminEdit($group_id=null){
        if(request()->isPost()){
            $data = input('post.');
            $pwd=input('post.pwd');

            $map['admin_id'] = array('neq',input('post.admin_id'));
            $where['admin_id'] = input('post.admin_id');
            // if(input('post.username')){
            //     $map['username'] = input('post.username');
            //     $check_user = Users::get($map);
            //     if ($check_user) {
            //         return $result = ['code'=>0,'msg'=>lang('The user has already existed, please reenter the username!')];
            //     }
            // }
            if(empty($data['email']) || !is_email($data['email'])){
                return array('code'=>0,'msg'=>lang('Please enter the correct mailbox address.'));
            }
            $email = Users::getEmail($where['admin_id']); 
            /*验证邮箱是否唯一*/
            if($email != $data['email'] && Users::validEmail($data['email'])){
                return array('code'=>0,'msg'=>lang('this email has been used'));
            }
            if ($pwd){
                $data['pwd']=input('post.pwd','','md5');
                $data['password'] = $data['pwd'];
            }else{
                unset($data['pwd']);
            }
            $msg = $this->validate($data,'Users');
            if($msg!='true'){
                return $result = ['code'=>0,'msg'=>$msg];
            }
            $data['group_id'] = $group_id;
            if(Users::update($data)){
                /*同步到ucenter*/
                $data['condition'] = $email;
                
                $ucenter = new \clt\Ucenter(); 
                $uid = $ucenter->editUser($data); //修改
            }
            //session('username',$data['username']);
            //$avatar = $data['avatar']==''?'/static/admin/images/0.jpg':$data['avatar'];
            //session('avatar',$avatar);
            return $result = ['code'=>1,'msg'=>lang('The data is saved successfully!'),'url'=>$this->backUrl];
        }else{
            
            $auth_group = AuthGroup::group($this->user['group_id']);
            $info = Users::get(['admin_id'=>input('admin_id')]);
            $this->assign('info', $info->toJson());
            $this->assign('authGroup',$auth_group);
            $this->assign('group_id',$info['group_id']);
            $this->assign('sup_id',$info['sup_id']);
            $this->assign('title',lang('Edit User'));
            $this->assign('users',Users::isAdmin($this->User_id) ? Users::getUserLists(input('admin_id')) : $this->User_id );
            return view('adminform');
        }
    }
    /*修改密码*/
    public function editpaw(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $admin = Users::get($this->User_id);
            if(!$admin){
                return ['code'=>0,'msg'=>lang("The account number does not exist!"),'url'=>U('login/logout')];
            }
            if(md5($data['oldpassword']) != $admin['pwd']){
                return ['code'=>0,'msg'=>lang("It's wrong to enter the old password!")];
            }
            if(!check_password($data['password'])){
                return ['code'=>0,'msg'=>lang('The password must be greater than 6 bits, less than 15 bits.')];
            }
            if($data['password'] != $data['repassword']){
                return ['code'=>0,'msg'=>lang("The two input password is not consistent!")];
            }
            $admin->pwd = md5($data['password']);
            if($admin->save()){
                $ucenter = new \clt\Ucenter;
                $ucenter->editPassword($admin->email,$admin->pwd);
                return ['code'=>1,'msg'=>lang("Password modification is successful!"),'url'=>U('index/index')];
            }
            return ['code'=>0,'msg'=>lang("Password modification failed!")];
        }
        $this->assign('title',lang('Change Password'));
        return $this->fetch();
    }
    /*-----------------------用户组管理----------------------*/
    //用户组管理
    public function admingroup(){
        if(request()->isPost()){
            $list = AuthGroup::all();
            return $result = ['code'=>0,'msg'=>lang('Request success.'),'data'=>$list,'rel'=>1];
        }
        return view('admingroup');
    }
    //删除管理员分组
    public function groupDel(){
        AuthGroup::destroy(['group_id'=>input('id')]);
        return $result = ['code'=>1,'msg'=>lang('Delete success!')];
    }
    //添加分组
    public function groupAdd(){
        if(request()->isPost()){
            $data=input('post.');
            $data['addtime']=time();
            $data['discount'] = intval($data['discount']);
            if($data['discount'] <= 0){
                $data['discount'] = 10;
            }elseif($data['discount'] > 100){
                $data['discount'] = 100;
            }
            AuthGroup::create($data);
            $result['msg'] = lang('The user group has been added successfully!');
            $result['url'] = url('admingroup');
            $result['code'] = 1;
            return $result;
        }else{
            $this->assign('title',lang('Add user groups'));
            $this->assign('info','null');
            return $this->fetch('groupform');
        }
    }
    //修改分组
    public function groupEdit(){
        if(request()->isPost()) {
            $data=input('post.');
            $data['discount'] = intval($data['discount']);
            if($data['discount'] <= 0){
                $data['discount'] = 10;
            }elseif($data['discount'] > 100){
                $data['discount'] = 100;
            }
            AuthGroup::update($data);
            $result = ['code'=>1,'msg'=>lang('The user group has been modified successfully!'),'url'=>url('admingroup')];
            return $result;
        }else{
            $id = input('id');
            $info = AuthGroup::get(['group_id'=>$id]);
            $this->assign('info', json_encode($info,true));
            $this->assign('title',lang('Edit user group'));
            return $this->fetch('groupform');
        }
    }
    //分组配置规则
    public function groupAccess(){
        $nav = new Leftnav();
        $admin_rule=db('auth_rule')->field('id,pid,title')->order('sort asc')->select();
        $rules = db('auth_group')->where('group_id',input('id'))->value('rules');
        $arr = $nav->auth($admin_rule,$pid=0,$rules);
        $arr[] = array(
            "id"=>0,
            "pid"=>0,
            "title"=>lang('All'),
            "open"=>true
        );
        $this->assign('data',json_encode($arr,true));
        return $this->fetch('groupaccess');
    }
    public function groupSetaccess(){
        $rules = input('post.rules');
        if(empty($rules)){
            return array('msg'=>lang('Please choose the permissions!'),'code'=>0);
        }
        $data = input('post.');
        if(AuthGroup::update($data)){
            return array('msg'=>lang('The permissions are configured successfully!'),'url'=>url('admingroup'),'code'=>1);
        }else{
            return array('msg'=>lang('Save the error'),'code'=>0);
        }
    }

    /********************************权限管理*******************************/
    public function adminRule(){
        if(request()->isPost()){
            $nav = new Leftnav();
            $arr = cache('authRuleList');
            if(!$arr){
                $authRule = authRule::all(function($query){
                    $query->order('sort', 'asc');
                });
                $arr = $nav->menu($authRule);
                cache('authRuleList', $arr, 3600);
            }
            return $result = ['code'=>0,'msg'=>lang('Request success.'),'data'=>$arr,'rel'=>1];
        }
        return view('adminrule');
    }
    public function ruleAdd(){
        if(request()->isPost()){
            $data = input('post.');
            $data['addtime'] = time();
            authRule::create($data);
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            return $result = ['code'=>1,'msg'=>lang('Permission to add success!'),'url'=>url('adminrule')];
        }else{
            $nav = new Leftnav();
            $arr = cache('authRuleList');
            if(!$arr){
                $authRule = authRule::all(function($query){
                    $query->order('sort', 'asc');
                });
                $arr = $nav->menu($authRule);
                cache('authRuleList', $arr, 3600);
            }
            $this->assign('admin_rule',$arr);//权限列表
            return $this->fetch('ruleadd');
        }
    }
    public function ruleOrder(){
        $auth_rule=db('auth_rule');
        $data = input('post.');
        if($auth_rule->update($data)!==false){
            cache('authRuleList', NULL);
            cache('authRule', NULL);
            return $result = ['code'=>1,'msg'=>lang('The sort update is successful!'),'url'=>url('adminrule')];
        }else{
            return $result = ['code'=>0,'msg'=>lang('The sort update failed!')];
        }
    }
    //设置权限菜单显示或者隐藏
    public function ruleState(){
        $id=input('post.id');
        $menustatus=input('post.menustatus');
        if(db('auth_rule')->where('id='.$id)->update(['menustatus'=>$menustatus])!==false){
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            return ['status'=>1,'msg'=>lang('Set up successfully.')];
        }else{
            return ['status'=>0,'msg'=>lang('Setup failed.')];
        }
    }
    //设置权限是否验证
    public function ruleTz(){
        $id=input('post.id');
        $authopen=input('post.authopen');
        if(db('auth_rule')->where('id='.$id)->update(['authopen'=>$authopen])!==false){
            cache('authRule', NULL);
            cache('authRuleList', NULL);
            return ['status'=>1,'msg'=>lang('Set up successfully.')];
        }else{
            return ['status'=>0,'msg'=>lang('Setup failed.')];
        }
    }
    public function ruleDel(){
        authRule::destroy(['id'=>input('param.id')]);
        cache('authRule', NULL);
        cache('authRuleList', NULL);
        return $result = ['code'=>1,'msg'=>lang('Delete success!')];
    }

    public function ruleEdit(){
        if(request()->isPost()) {
            $datas = input('post.');
            if(authRule::update($datas)) {
                cache('authRule', NULL);
                cache('authRuleList', NULL);
                return json(['code' => 1, 'msg' => lang('The data is saved successfully!'), 'url' => url('adminrule')]);
            } else {
                return json(['code' => 0, 'msg' =>lang('Data save failed!')]);
            }
        }else{
            $admin_rule = authRule::get(function($query){
                $query->where(['id'=>input('id')])->field('id,href,title,icon,sort,menustatus,pid');
            });
            $this->assign('rule',$admin_rule);
            $arr = cache('authRuleList');
            if(!$arr){
                $nav = new Leftnav();
                $authRule = authRule::all(function($query){
                    $query->order('sort', 'asc');
                });
                $arr = $nav->menu($authRule);
                cache('authRuleList', $arr, 3600);
            }
            $this->assign('rules',$arr);//权限列表
            return $this->fetch('ruleedit');
        }
    }
    /*用户资料*/
    public function userinfo(){
        if($this->request->isPost()){
            $data = $this->request->post();

            if(empty($data['email']) || !is_email($data['email'])){
                return array('code'=>0,'msg'=>lang('Please enter the correct mailbox address.'));
            }
            $map['email'] = $data['email'];
            $map['admin_id'] = array('neq',$this->User_id);
            if(db('users')->where($map)->count()){
                return array('code'=>0,'msg'=>lang('The name of the user has been occupied'));
            }
            // if(empty($data['tel']) || !is_mobile($data['tel'])){
            //     return array('code'=>0,'msg'=>lang('Please enter the correct contact phone.'));
            // }
            if(empty($data['company'])){
                return array('code'=>0,'msg'=>lang('Please enter your company name.'));
            }
            if(db('users')->where('admin_id',$this->User_id)->update($data) === false){
               
                return array('code'=>0,'msg'=>lang('Failure to modify user data'));
            }
             $data['condition'] =  $data['email'];
            $ucenter = new \clt\Ucenter(); 
             $uid = $ucenter->editUser($data); //修改
            session('email',$data['email']);
            return array('code'=>1,'msg'=>lang('Modify user data successfully'));
        }
        $info = Users::get(['admin_id'=>$this->User_id]);
        $this->assign('info',$info);
        $this->assign('title',lang('User Profile'));
        return $this->fetch();
    }
    /*导出数据*/
    public function exports($data){
        $heade=lang('Mailbox/Telephone/Company Name/Company Address/Position');
        $heades = explode("/", $heade);
        $base = array();
        if($data){
            foreach($data as $vo){
                $base[] = array(
                    'email'=>$vo['email'],
                    'mobile'=>$vo['mobile'],
                    'company'=>$vo['company'],
                    'address'=>$vo['address'],
                    'position'=>$vo['position'],
                ); 
            }
        }
        return parent::export($this->title,$heades,$base);
    }
}